#include "MainPlot.h"
#include <qwt_wheel.h>
#include <qwt_plot_canvas.h>
#include <QEvent>
#include <QMouseEvent>
#include <qwt_scale_engine.h>


//-------------------------------------

MainPlot::MainPlot( QWidget * parent ) :
    QwtPlot( parent )
{
    axX = xBottom;
    axY = yLeft;
    canvas()->installEventFilter( this );
}

//-------------------------------------

bool MainPlot::eventFilter( QObject * object, QEvent * e )
{
    if( object == canvas() )
    {
        QwtPlotCanvas * cnv = static_cast< QwtPlotCanvas* >( object );
        QMouseEvent * me = static_cast< QMouseEvent* >( e );
        QRect cg = cnv->geometry();
        if( e->type() == QEvent::MouseButtonPress )
        {
            isDragging = true;
            cursor = cnv->cursor();
            cnv->setCursor( Qt::ClosedHandCursor );

            cursorStartDragPosX = me->pos().x() - cg.x();
            cursorStartDragPosY = me->pos().y() - cg.y();
            kx = invTransform( axX, cursorStartDragPosX + 1 ) - invTransform( axX, cursorStartDragPosX );
            ky = invTransform( axY, cursorStartDragPosY + 1 ) - invTransform( axY, cursorStartDragPosY );
            QwtScaleMap sm = canvasMap( axX );
            lBnd = sm.s1();
            rBnd = sm.s2();
            sm = canvasMap( axY );
            bBnd = sm.s1();
            tBnd = sm.s2();
        }
        if( e->type() == QEvent::MouseMove )
        {
            if( isDragging )
            {
                double dx = -( me->pos().x() - cg.x() - cursorStartDragPosX ) * kx;
                setAxisScale( axX, lBnd + dx, rBnd + dx );
                double dy = -( me->pos().y() - cg.y() - cursorStartDragPosY ) * ky;
                setAxisScale( axY, bBnd + dy, tBnd + dy );
                replot();
            }

        }
        if( e->type() == QEvent::MouseButtonRelease )
        {
            isDragging = false;
            cnv->setCursor( cursor );
        }
    }
    return QwtPlot::eventFilter( object, e );
}

//-------------------------------------

void MainPlot::SetAxisScaleEngie( QwtPlot::Axis ax, ScEngType t )
{
    switch( t )
    {
        case Linear:
            setAxisScaleEngine( ax, new QwtLinearScaleEngine() );;
            break;

        case Log10:
            setAxisScaleEngine( ax, new QwtLog10ScaleEngine() );
            break;
    }
    replot();
}

//-------------------------------------
